"""
Pydantic 模型（API 输入输出）

与 SQLAlchemy 模型分离，职责更清晰
"""

from pydantic import BaseModel, EmailStr, Field
from typing import Optional, List
from datetime import datetime


# ========== 标签模型 ==========

class TagBase(BaseModel):
    """标签基础模型"""
    name: str = Field(..., min_length=1, max_length=50)
    description: Optional[str] = Field(None, max_length=200)


class TagCreate(TagBase):
    """标签创建（输入）"""
    pass


class TagResponse(TagBase):
    """标签响应（输出）"""
    id: int
    created_at: datetime
    
    class Config:
        from_attributes = True


# ========== 用户模型 ==========

class UserBase(BaseModel):
    """用户基础模型"""
    username: str = Field(..., min_length=3, max_length=50)
    email: EmailStr
    full_name: Optional[str] = None


class UserCreate(UserBase):
    """用户创建（输入）"""
    password: str = Field(..., min_length=8)


class UserUpdate(BaseModel):
    """用户更新（输入）"""
    email: Optional[EmailStr] = None
    full_name: Optional[str] = None
    password: Optional[str] = None


class UserResponse(UserBase):
    """用户响应（输出）"""
    id: int
    is_active: bool
    is_superuser: bool
    created_at: datetime
    
    class Config:
        from_attributes = True


class UserWithPosts(UserResponse):
    """用户响应（包含文章列表）"""
    posts: List["PostResponse"] = []


# ========== 文章模型 ==========

class PostBase(BaseModel):
    """文章基础模型"""
    title: str = Field(..., min_length=1, max_length=200)
    content: Optional[str] = None
    is_published: bool = False


class PostCreate(PostBase):
    """文章创建（输入）"""
    tag_ids: List[int] = []  # 标签 ID 列表


class PostUpdate(BaseModel):
    """文章更新（输入）"""
    title: Optional[str] = Field(None, min_length=1, max_length=200)
    content: Optional[str] = None
    is_published: Optional[bool] = None
    tag_ids: Optional[List[int]] = None


class PostResponse(PostBase):
    """文章响应（输出）"""
    id: int
    author_id: int
    view_count: int
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True


class PostWithDetails(PostResponse):
    """文章响应（包含作者和标签）"""
    author: UserResponse
    tags: List[TagResponse] = []


# 解决循环引用
UserWithPosts.model_rebuild()

